# -*- coding: utf-8 -*-
# @Time    : 2022/10/30 14:11
# @Author  : 限量老
import random
from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.utils.form_总 import OrderModelForm
from app01.utils.pagination分页组件 import Pagination


def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')

    # 分页
    page_object = Pagination(request, queryset)  # 生成分页对象        #分页须加

    form = OrderModelForm()
    context = {
        'form': form,
        # 'queryset':queryset,
        'queryset': page_object.page_queryset,  # 分页完的数据       #分页须加
        'page_string': page_object.html()  # 生成页码               #分页须加
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):  # 接收请求
    '''新建订单(Ajax请求)'''
    # 1.用户发送过来的数据进行校验
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 额外添加一些不是用户输入的值(自己计算出来):
        # 订单号自己生成:
        form.instance.oid = datetime.now().strftime('%Y%m%d-%H%M%S-') + str(
            random.randint(1000, 9999))  # instance:取得当前form

        # 管理员:当前登录的管理员,去session中获取
        form.instance.admin_id = request.session['info']['id']

        print(form.cleaned_data)
        form.save()

        return JsonResponse({'status': True})
        # return HttpResponse(json.dumps({'status':True}))#等同上

    return JsonResponse({'status': False, 'error': form.errors})


def order_delete(request):
    """删除订单"""
    uid = request.GET.get('uid')
    # print(uid)
    exist = models.Order.objects.filter(id=uid).exists()
    if not exist:
        return JsonResponse({'status': False, 'error': '删除失败,数据不存在'})
    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({'status': True})


def order_detail(request):
    '''根据ID获取订单详细'''

    '''方式1'''
    '''uid = request.GET.get('uid')
    #print(uid)
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({'status': False, 'error': '数据不存在'})
    # 从数据库中获取到一个对象,row_object
    result = {
        'status': True,
        'data': {
            'title': row_object.title,
            'price': row_object.price,
            'status': row_object.status,
        }
    }
    return JsonResponse(result)'''

    '''方式2'''
    uid = request.GET.get('uid')
    row_dict = models.Order.objects.filter(id=uid).values('title', 'price', 'status').first()
    print(row_dict)
    if not row_dict:
        return JsonResponse({'status': False, 'error': '数据不存在'})

    result = {
        'status': True,
        'data': row_dict,
    }
    return JsonResponse(result)


@csrf_exempt
def order_edit(request):
    '''编辑订单'''
    uid = request.GET.get('uid')
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({'status': False, 'tips': '数据不存在,请刷新重试'})

    form = OrderModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})  # 全局错误提示
